package com.itheima.search.service.impl;

import com.heima.model.common.behavior.pojos.ApBehaviorEntry;
import com.heima.model.common.dtos.HistorySearchDTO;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.dtos.UserSearchDTO;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.search.pojo.ApUserSearch;
import com.heima.model.common.threadlocal.AppThreadLocalUtils;
import com.heima.model.common.user.pojo.ApUser;
import com.itheima.common.exception.CustException;
import com.itheima.feigns.BehaviorFeign;
import com.itheima.search.service.ApUserSearchService;
import com.mongodb.client.result.DeleteResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class ApUserSearchServiceImpl implements ApUserSearchService {
    @Autowired
    MongoTemplate mongoTemplate;
    @Autowired
    BehaviorFeign behaviorFeign;
    @Override
    @Async("taskExecutor")
    public void insert(UserSearchDTO userSearchDto) {
        //检查参数
        if (userSearchDto.getEntryId()==null || userSearchDto.getSearchWords()==null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        String searchWords = userSearchDto.getSearchWords();
        Integer entryId = userSearchDto.getEntryId();
        //查找行为实体类
//        ApBehaviorEntry entry = mongoTemplate.findOne(Query.query(Criteria.where("_id").is(entryId)), ApBehaviorEntry.class);
//        if (entry==null){
//            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
//        }
        ResponseResult<ApBehaviorEntry> result = behaviorFeign.findByUserIdOrEquipmentId(entryId, userSearchDto.getEquipmentId());
        if (!result.checkCode()){
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        ApBehaviorEntry entry = result.getData();
        if (entry==null){
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        log.info("ApUserSearchServiceImpl insert entryId:{}, searchWords:{}", entryId, searchWords);
        //查询用户当前的关键词是否存在
        ApUserSearch apUserSearch = mongoTemplate.findOne(Query.query(Criteria.where("entryId").is(String.valueOf(entryId)).and("keyword").is(searchWords)), ApUserSearch.class);
        //存在更新时间
        if (apUserSearch!=null){
            Update update = new Update();
            update.set("createdTime",new Date());
            mongoTemplate.updateMulti(Query.query(Criteria.where("_id").is(apUserSearch.getId())),update,ApUserSearch.class);
        }else {
            ApUserSearch apUserSearch1 = new ApUserSearch();
            apUserSearch1.setEntryId(String.valueOf(entryId));
            apUserSearch1.setKeyword(searchWords);
            apUserSearch1.setCreatedTime(new Date());
            ApUserSearch save = mongoTemplate.save(apUserSearch1);
        }



    }

    @Override
    public ResponseResult findUserSearch(UserSearchDTO userSearchDto) {
        //检查参数
        if (userSearchDto==null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (userSearchDto.getMinBehotTime()==null){//如果没有最小时间 设置一个
            userSearchDto.setMinBehotTime(new Date());
        }
        //查询行为实体
        List<ApUserSearch> apUserSearches= new ArrayList<>();
        ApUser user = AppThreadLocalUtils.getUser();
        ResponseResult<ApBehaviorEntry> result = behaviorFeign.findByUserIdOrEquipmentId(user == null ? null : user.getId(), userSearchDto.getEquipmentId());
        if (!result.checkCode()){
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        ApBehaviorEntry entry = result.getData();
        if (entry==null){
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        log.info("ApUserSearchServiceImpl findUserSearch ");
        //查询10条数据

        apUserSearches = mongoTemplate.find(Query.query(Criteria.where("entryId").is(String.valueOf(entry.getRefId())).and("createdTime").lt(userSearchDto.getMinBehotTime()))
                .with(Sort.by(Sort.Direction.DESC, "createdTime")).limit(userSearchDto.getPageSize()), ApUserSearch.class);
        return ResponseResult.okResult(apUserSearches);

    }

    @Override
    public ResponseResult delUserSearch(HistorySearchDTO dto) {
        if(dto.getId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApUser user = AppThreadLocalUtils.getUser();
        ResponseResult<ApBehaviorEntry> behaviorEntryResult = behaviorFeign.findByUserIdOrEquipmentId(user == null ? null : user.getId(), dto.getEquipmentId());
        if(!behaviorEntryResult.checkCode()){
            return ResponseResult.errorResult(AppHttpCodeEnum.REMOTE_SERVER_ERROR,"远程调用行为服务失败");
        }
        ApBehaviorEntry behaviorEntry = behaviorEntryResult.getData();
        if(behaviorEntry == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"行为实体数据不存在");
        }
        System.out.println(behaviorEntry.getRefId());
        System.out.println(dto.getId());
        DeleteResult remove = mongoTemplate.remove(Query.query(Criteria.where("_id").is(dto.getId()).and("entryId").is(String.valueOf(behaviorEntry.getRefId()))), ApUserSearch.class);
        long deletedCount = remove.getDeletedCount();
        System.out.println("deletedCount = " + deletedCount);
        return ResponseResult.okResult();
    }
}
